// utils/notificationService.js
import Stomp from 'stompjs';
import {
	showAppPush
} from '@/components/APPPush/index.js';
// 引入统一配置文件
import config from '@/config/index.js';
// --- 配置 ---
const WS_BASE_URL = config.websocketURL; // WebSocket服务端点
let stompClient = null;
let currentUserId = null;
let currentUserToken = null;
let socketTask = null; // 仅APP端使用：uni.connectSocket 返回的 SocketTask
let webSocket = null; // 仅H5端使用：原生 WebSocket 实例

let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 5;
const RECONNECT_DELAY = 5000;

function log(message, type = 'info', data = null) {
	const prefix = `[通知服务] [${new Date().toLocaleTimeString()}]`;
	console[type === 'error' ? 'error' : 'log'](`${prefix} ${message}`, data || '');
}

function handleNotificationDisplay(notificationData) {
	log('准备显示应用内推送通知', 'info', notificationData);

	let modalTitle = '新通知';
	let modalContent = '您有一条新消息，请查看。';
	let modalType = 'REPLY_COMMENT'; // 默认
	let targetUserId = null;
	let targetNickName = null;
	let avatar = '';

	if (notificationData) {
		modalTitle = notificationData.title || (notificationData.notificationType === 'NEW_CHAT_MESSAGE' ? (
			notificationData.senderNickname || '新消息') : modalTitle);
		modalContent = notificationData.contentPreview || notificationData.content || modalContent;

		if (notificationData.notificationType === 'NEW_CHAT_MESSAGE') {
			modalType = 'OPEN_CHAT';
			targetUserId = notificationData.senderId;
			targetNickName = notificationData.senderNickname || '对方';
			avatar = notificationData.senderAvatar || avatar;
		} else if (notificationData.notificationType === 'REPLY_COMMENT') {
			modalType = 'REPLY_COMMENT';
		}
	}

	const params = {
		inApp: true,
		voice: true,
		vibration: true,
		userId: targetUserId,
		nickName: targetNickName,
		messageType: modalType,
		messageTitle: modalTitle,
		messageContent: modalContent,
		messageImage: avatar
	};
	showAppPush(params);
}

function connectWebSocket() {
	return new Promise((resolve, reject) => {
		if (!currentUserId || !currentUserToken) {
			return reject(new Error('用户ID和令牌是连接所必需的。'));
		}

		if (stompClient && stompClient.connected) {
			return resolve('STOMP 已连接。');
		}

		// 清理旧连接
		handleDisconnect(false);

		log(`尝试以用户 ${currentUserId} 连接...`, 'info');

		// #ifdef APP-PLUS
		socketTask = uni.connectSocket({
			url: WS_BASE_URL,
			fail: (err) => reject(new Error(`uni.connectSocket 失败: ${err.errMsg}`))
		});
		const wsAdapter = {
			send: (data) => socketTask && socketTask.send({
				data
			}),
			close: () => socketTask && socketTask.close(),
		};
		socketTask.onOpen(() => {
			if (wsAdapter.onopen) wsAdapter.onopen();
		});
		socketTask.onMessage((res) => {
			if (wsAdapter.onmessage) wsAdapter.onmessage({
				data: res.data
			});
		});
		socketTask.onClose((res) => {
			if (wsAdapter.onclose) wsAdapter.onclose(res);
			handleDisconnect(true);
		});
		socketTask.onError((err) => {
			if (wsAdapter.onerror) wsAdapter.onerror(err);
			handleDisconnect(true);
		});
		// #endif

		// #ifdef H5
		try {
			webSocket = new WebSocket(WS_BASE_URL);
		} catch (e) {
			return reject(new Error(`创建 WebSocket 失败: ${e.message}`));
		}
		const wsAdapter = webSocket; // H5原生WebSocket直接兼容Stomp.js

		wsAdapter.onclose = () => handleDisconnect(true);
		wsAdapter.onerror = () => handleDisconnect(true);
		// #endif

		stompClient = Stomp.over(wsAdapter);
		stompClient.debug = null; // 关闭STOMP的console.log输出

		const connectHeaders = {
			'Authorization': 'Bearer ' + currentUserToken
		};

		stompClient.connect(connectHeaders, (frame) => {
			log('STOMP 已连接。', 'success');
			reconnectAttempts = 0;

			const userQueue = `/user/queue/notifications`;
			stompClient.subscribe(userQueue, (message) => {
				try {
					const notificationData = JSON.parse(message.body);
					handleNotificationDisplay(notificationData);
				} catch (e) {
					log('处理消息失败: ' + e.message, 'error');
				}
			});
			resolve('STOMP 已连接。');
		}, (error) => {
			const errMsg = `STOMP 连接失败: ${error.headers ? error.headers.message : error}`;
			log(errMsg, 'error');
			handleDisconnect(true);
			reject(new Error(errMsg));
		});
	});
}

function handleDisconnect(shouldReconnect = false) {
	if (stompClient) {
		try {
			stompClient.disconnect(() => log('STOMP 已断开。'));
		} catch (e) {}
		stompClient = null;
	}
	// #ifdef APP-PLUS
	if (socketTask) {
		try {
			socketTask.close();
		} catch (e) {}
		socketTask = null;
	}
	// #endif
	// #ifdef H5
	if (webSocket) {
		try {
			webSocket.close();
		} catch (e) {}
		webSocket = null;
	}
	// #endif

	console.log(shouldReconnect, currentUserId, currentUserToken, '=======================查看参数是否符合进入条件判断');
	if (shouldReconnect && currentUserId && currentUserToken) {
		console.log(123, '进入重连代码================================');
		if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
			reconnectAttempts++;
			log(`准备在 ${RECONNECT_DELAY / 1000}秒后重连... (第 ${reconnectAttempts} 次)`, 'info');
			setTimeout(() => connectWebSocket().catch(err => log('重连失败。', 'error')), RECONNECT_DELAY);
		} else {
			log('已达到最大重连次数。', 'error');
		}
	}
}

export default {
	connect(userId, token) {
		currentUserId = userId + '';
		currentUserToken = token;
		reconnectAttempts = 0;
		return connectWebSocket();
	},
	disconnect() {
		log('请求主动断开连接...', 'info');
		currentUserToken = null; // 清除token，阻止重连
		reconnectAttempts = MAX_RECONNECT_ATTEMPTS;
		handleDisconnect(false);
	},
	isConnected() {
		return !!(stompClient && stompClient.connected);
	}
};